package com.coship.vas.dapg.util;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

/**
 * XML 解析器
 * 
 * @author 904912
 * 
 */
public class XMLParser {
    private final static Logger logger = Logger.getLogger(XMLParser.class);

    /**
     * 
     * @param xmlName
     *            <p>
     *            类似 /am.xml
     *            </p>
     * @return
     * @throws Exception
     */
    public static File initXml(String xmlName) throws Exception {
        String path = XMLParser.class.getResource(xmlName).getFile();
        if (System.getProperty("os.name").startsWith("Windows")) {
            path = path.substring(1);
        }
        path = URLDecoder.decode(path, "UTF-8");
        File f = new File(path);
        return f;
    }

    /**
     * xml转换为document
     * 
     * @param filePath
     *            File
     * @return
     * @throws Exception
     */
    public static Document getDocument(File filePath) throws Exception {
        Document document = null;
        SAXReader reader = new SAXReader();
        if (filePath != null && filePath.exists()) {
            document = reader.read(filePath);
        }
        return document;
    }

    /**
     * xmlString转换为document
     * 
     * @param filePath
     *            xmlString
     * @return
     * @throws Exception
     */
    public static Document getDocument(String filePath) throws Exception {
        Document document = null;
        SAXReader reader = new SAXReader();
        if (filePath != null && !"".equals(filePath)) {
            document = reader.read(new ByteArrayInputStream(filePath.getBytes("UTF-8")));
        }
        return document;
    }

    /**
     * 
     * @param document
     * @param parentElementName
     *            父节点，也可以是根节点 格式//a/Asset/Metadata, a为根目录
     * @param childName
     *            子节点名称
     * @return 返回parentElementName所有子节点的Element
     * @throws DocumentException
     */
    @SuppressWarnings("unchecked")
	public static List<List<Element>> getElementList(Document document, String parentElementName, String childName)
            throws DocumentException {
        List<Element> elementList = new ArrayList<Element>();
        List<List<Element>> elementCollents = new ArrayList<List<Element>>();
        if (parentElementName == null) {
            return elementCollents;
        }
        List<Element> list = document.selectNodes(parentElementName);
        for (Element e : list) {
            elementList = e.elements(childName.trim());
            elementCollents.add(elementList);
        }
        return elementCollents;
    }

    // ============END============================================================================

    @SuppressWarnings("unchecked")
	public static List<List<Element>> getXMLChildElementList(String parentElementName, File filePath, String childName)
            throws Exception {
        List<Element> elementList = new ArrayList<Element>();
        SAXReader reader = new SAXReader();
        List<List<Element>> elementCollents = new ArrayList<List<Element>>();
        if (parentElementName == null) {
            return elementCollents;
        }
        try {
            if (filePath != null && filePath.exists()) {
                Document document = reader.read(filePath);
                List<Element> list = document.selectNodes(parentElementName);
                for (Element e : list) {
                    elementList = e.elements(childName.trim());
                    elementCollents.add(elementList);
                }
            }
        } catch (DocumentException de) {
            throw de;
        }
        return elementCollents;
    }

    /**
     * 
     * @param parentElementName
     *            父节点，也可以是根节点 格式//a/Asset/Metadata, a为根目录
     * @param stream
     * 
     * @param childName
     *            子节点名称
     * @return 返回parentElementName所有子节点的Element
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
	public static List<List<Element>> getXMLChildElementList(String parentElementName, InputStream stream,
            String childName) throws Exception {
        List<Element> elementList = new ArrayList<Element>();
        SAXReader reader = new SAXReader();
        List<List<Element>> elementCollents = new ArrayList<List<Element>>();
        if (parentElementName == null) {
            return elementCollents;
        }
        try {
            if (stream != null) {
                Document document = reader.read(stream);
                List<Element> list = document.selectNodes(parentElementName);
                for (Element e : list) {
                    elementList = e.elements(childName.trim());
                    elementCollents.add(elementList);
                }
            }
        } catch (DocumentException de) {
            logger.error("解析.xml出现错误,cause:", de);
            throw new Exception();
        }
        return elementCollents;
    }

    /**
     * 获取所有节点parentElementName
     * 
     * @param document
     * @param parentElementName
     * @return
     */
    @SuppressWarnings("unchecked")
	public static List<Element> getCurrentElement(Document document, String parentElementName) {
        List<Element> elementList = new ArrayList<Element>();
        if (document == null) {
            return elementList;
        }
        if (parentElementName == null || "".equals(parentElementName)) {
            return elementList;
        }
        elementList = document.selectNodes(parentElementName);
        return elementList;
    }

    /**
     * 获取ADI节点//ADI/Asset/Asset/Metadata文件下所有子节点
     * 
     * @param nodeName
     *            格式：//ADI/Asset/Asset/Metadata
     * @return
     * @throws DocumentException
     */
    @SuppressWarnings("unchecked")
	public static Map<String, List<Element>> getADIElementMap(String nodeName, InputStream stream)
            throws DocumentException {

        SAXReader reader = new SAXReader();

        // 存放movie 和 poster 类型 List
        Map<String, List<Element>> appMap = new HashMap<String, List<Element>>();

        // 存放poster类型
        List<Element> posterCompise = new ArrayList<Element>();

        // 存放movie类型
        List<Element> movieCompise = new ArrayList<Element>();
        Document document = reader.read(stream);
        List<Element> list = document.selectNodes(nodeName);
        for (Element e : list) {
            Element AMS = e.element("AMS");
            if (AMS == null) {
                return appMap;
            } else {
                String asset_Class = getElementArrtiueValue(AMS, "Asset_Class");
                if ("poster".equals(asset_Class)) {
                    posterCompise.add(e);
                } else if ("movie".equals(asset_Class)) {
                    movieCompise.add(e);
                }
            }
        }

        appMap.put("poster", posterCompise);
        appMap.put("movie", movieCompise);

        return appMap;

    }

    /**
     * 
     * @param parentElementName
     *            父节点，也可以是根节点 格式//a/Asset/Metadata, a为根目录
     * @param xmlString
     *            xml文件读取后的string
     * @param childName
     *            子节点名称
     * @return 返回parentElementName所有子节点的Element
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
	public static List<List<Element>> getXMLChildElementList(String parentElementName, String xmlString,
            String childName) throws Exception {
        List<Element> elementList = new ArrayList<Element>();
        SAXReader reader = new SAXReader();
        List<List<Element>> elementCollents = new ArrayList<List<Element>>();
        if (parentElementName == null) {
            return elementCollents;
        }
        try {
            if (xmlString != null && !"".equals(xmlString)) {
                Document document = reader.read(new ByteArrayInputStream(xmlString.getBytes("UTF-8")));
                List<Element> list = document.selectNodes(parentElementName);
                for (Element e : list) {
                    elementList = e.elements(childName.trim());
                    elementCollents.add(elementList);
                }
            }
        } catch (DocumentException de) {
            logger.error("解析.xml出现错误,cause:", de);
            throw de;
        }
        return elementCollents;
    }

    /**
     * 获取节点属性
     * 
     * @param element
     * @param arrtiueName
     * @return
     */
    public static String getElementArrtiueValue(Element element, String arrtiueName) {
        String arrtiueValue = "";
        if (element != null && arrtiueName != null) {
            arrtiueValue = element.attributeValue(arrtiueName.trim());
            if (arrtiueValue == null) {
                return "";
            }
        }
        return arrtiueValue;
    }

    public static Document getDocument(InputStream stream) throws Exception {
        SAXReader reader = new SAXReader();
        Document document = null;
        try {
            if (stream != null) {
                document = reader.read(stream);
            }
        } catch (DocumentException de) {
            throw new Exception();
        }
        return document;
    }

    public static Element getRootElement(InputStream stream) throws Exception {
        SAXReader reader = new SAXReader();
        Element rootElement = null;
        try {
            if (stream != null) {
                Document document = reader.read(stream);
                rootElement = document.getRootElement();
            }
        } catch (DocumentException de) {
            logger.error("解析.xml出现错误,cause:", de);
            throw new Exception();
        }
        return rootElement;
    }

    public static void main(String[] args) throws Exception {
        
        File file = initXml("/am.xml");
         Document doc = getDocument(file);
         List<List<Element>>  list  =   getElementList(doc,"//config/services","service" );
         for(List<Element> el  : list  ){
             for(Element  e : el){
                 System.out.println(e.attributeValue("id"));
                 System.out.println(e.attributeValue("medianame"));
             }
             
             
         }
        
    }

}
